//
//  D_SearchMusicViewController.m
//  音悦咖
//
//  Created by dllo on 15/5/1.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "D_SearchMusicViewController.h"
#import "BaseHeader.h"
#import "D_MyMusicCollectionViewCell.h"
#import "D_AlerterUIview.h"
#import "AFNetworkHandler.h"
#import "L_Singleton.h"
#import "UMSocial.h"
#import "D_DataBase.h"
#import "PlayerModel.h"
#import "MBProgressHUD.h"
@interface D_SearchMusicViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate,MBProgressHUDDelegate>


@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, assign) NSInteger footerHight;
@property (nonatomic, assign) NSInteger sectionNum;
@property (nonatomic, assign) NSInteger tagNum;
@property (nonatomic, retain) NSMutableArray *tempUrlArr;
@property (nonatomic, retain) NSMutableArray *modelArr;
@property (nonatomic, retain) MBProgressHUD *progress;

@end

@implementation D_SearchMusicViewController
- (void)dealloc
{
    [_str release];
    [_arr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleLabel.text = @"搜索音乐";
    // 背景图片
    UIImageView *backImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    backImg.image = [UIImage imageNamed:@"musicbg.jpg"];
    backImg.alpha = 0.8;
    [self.view addSubview:backImg];
    [backImg release];
    
    // 调用菊花方法
    [self createProgress];
    
    // collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(335 , 50);
    //    layout.minimumLineSpacing = 30;
    
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
#pragma mark - footer
    //    layout.headerReferenceSize = CGSizeMake(355, 100);
    //    layout.footerReferenceSize = CGSizeMake(300, 50);
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 100) collectionViewLayout:layout];
    self.collection.backgroundColor = [UIColor clearColor];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [self.view addSubview:self.collection];
#pragma mark - 注册重用池
    [self.collection registerClass:[D_MyMusicCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    [self.collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.collection release];
    [layout release];
 
    
    [self getData];
    
}
#pragma mark - 菊花类
- (void)createProgress
{
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
        if ([AFStringFromNetworkReachabilityStatus(status) isEqualToString:@"Not Reachable"]) {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络没有连接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
        } else if ([AFStringFromNetworkReachabilityStatus(status) isEqualToString:@"Reachable via WWAN"]){
           
          self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.progress.labelText = @"稍等";
            self.progress.detailsLabelText = @"正在加载...";
            self.progress.delegate = self;
            [self.progress show:YES];
            
            for (UIView *v in self.view.subviews) {
                if (v.tag == 999999) {
                    [self.view bringSubviewToFront:v];
                }
            }
            
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前正使用数据流量" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
//            [alert release];
        }else if ([AFStringFromNetworkReachabilityStatus(status) isEqualToString:@"Reachable via WiFi"]){
            self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.progress.labelText = @"稍等";
            self.progress.detailsLabelText = @"正在加载...";
            self.progress.delegate = self;
            [self.progress show:YES];
       
            for (UIView *v in self.view.subviews) {
                if (v.tag == 999999) {
                    [self.view bringSubviewToFront:v];
                }
            }
//
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络为wifi网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [alert show];
//            [alert release];
           
        }
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

- (void)doSomething
{
    //你要进行的一些事
    sleep(2);
}




- (void)getData
{
    
    NSString *url = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@&page=1&size=50&app=ttpod&v=v7.9.4.2015052918&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=693b90d28eb38e80fa046681d1d0b72f82d8e708&idfa=87A61A73-95A5-4726-A46E-6C1AC01F020C&utdid=Vas%%2BEb1LSgIDAKYUphQoIHpk&alf=201200&bundle_id=com.ttpod.music",self.str];
    
//     NSString *str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"--------------%@",str);
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        
         self.arr = [NSMutableArray array];
        self.arr = [result objectForKey:@"data"];
        self.modelArr = [NSMutableArray array];
        self.modelArr = [PlayerModel arrayWithModelByArray:self.arr];
        if (self.arr.count < 1) {
            self.progress.hidden = YES;
            
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索的内容为空!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [alter show];
            [alter release];
            
        }else{
         self.progress.hidden = YES;
            
        [self.collection reloadData];
        
            
        }
    }];
    
   
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 || buttonIndex == 1) {
         [self.navigationController popToRootViewControllerAnimated:YES];
    }
}




#pragma mark - 头部大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(0, 0);
}

#pragma mark - 尾部方法协议
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if (section == self.sectionNum) {
        return CGSizeMake(0, self.footerHight);
    }
    return CGSizeMake(0, 0);
    
}
#pragma mark - footer/header 协议方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.backgroundColor = [UIColor grayColor];
        [header.layer setCornerRadius:20];
        header.alpha = 0.8;
        
        return header;
    }
    
    
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        footer.backgroundColor = [UIColor clearColor];
        [footer.layer setCornerRadius:10];
        // 分享按钮
        UIButton *share = [UIButton buttonWithType:UIButtonTypeSystem];
        share.frame = CGRectMake(SCREEN_WIDTH * 0.16, 20, 30, 30);
        share.backgroundColor = [UIColor clearColor];
        share.tag = indexPath.section;
        [share setImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
        [share addTarget:self action:@selector(shearchAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *shareLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.16, 55, 50, 20)];
        shareLable.text = @"分享";
        shareLable.font = [UIFont fontWithName:nil size:14];
        [footer addSubview:shareLable];
        [footer addSubview:share];
        [shareLable release];
        
        // 我喜欢按钮
        UIButton *myLovew = [UIButton buttonWithType:UIButtonTypeSystem];
        myLovew.frame = CGRectMake(SCREEN_WIDTH * 0.4, 20, 30, 30);
        myLovew.backgroundColor = [UIColor clearColor];
        [myLovew setImage:[[UIImage imageNamed:@"mylove"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
        [myLovew addTarget:self action:@selector(myLoveAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *myLovewLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.3866, 55, 50, 20)];
        myLovewLable.text = @"我喜欢";
        myLovew.tag = indexPath.section;
        myLovewLable.font = [UIFont fontWithName:nil size:14];
        [footer addSubview:myLovewLable];
        [footer addSubview:myLovew];
        [myLovewLable release];
        
        // 收藏
        UIButton *collect = [UIButton buttonWithType:UIButtonTypeSystem];
        collect.frame = CGRectMake(SCREEN_WIDTH * 0.666, 20, 30, 30);
        collect.backgroundColor = [UIColor clearColor];
        [collect setImage:[[UIImage imageNamed:@"save"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
        [collect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *collectLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.666, 55, 50, 20)];
        collectLable.text = @"收藏";
        collect.tag = indexPath.section;
        collectLable.font = [UIFont fontWithName:nil size:14];
        [footer addSubview:collectLable];
        [footer addSubview:collect];
        [collectLable release];
        
        // 删除
//        UIButton *delete = [UIButton buttonWithType:UIButtonTypeSystem];
//        delete.frame = CGRectMake(280, 20, 30, 30);
//        delete.backgroundColor = [UIColor clearColor];
//        [delete setImage:[[UIImage imageNamed:@"deletemusic"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
//        [delete addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
//        UILabel *deleteLable = [[UILabel alloc]initWithFrame:CGRectMake(280, 55, 50, 20)];
//        deleteLable.text = @"删除";
//        deleteLable.font = [UIFont fontWithName:nil size:14];
//        [footer addSubview:deleteLable];
//        [footer addSubview:delete];
//        [deleteLable release];
//     

        return footer;
    }
    return nil;
}

#pragma mark - 分享
- (void)shearchAction:(UIButton *)button
{
//    [D_AlerterUIview showAlert:@"分享成功!"];
    NSString *url = [[[self.arr[button.tag]objectForKey:@"url_list"] firstObject] objectForKey:@"url"];
    NSString *song = [self.arr[button.tag] objectForKey:@"singer_name"];
    
    NSString *str = [NSString stringWithFormat:@"请输入要分享的文字.......%@%@",url,song];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:SDK_KEY shareText:str shareImage:[UIImage imageNamed:@"lloo"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToQQ,nil] delegate:nil];
    
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatTimeline]];
  
}

#pragma mark - 我喜欢
- (void)myLoveAction:(UIButton *)button
{
//    [D_AlerterUIview showAlert:@"我喜欢!"];
    NSInteger num = button.tag;
    

        
        D_DataBase *data = [[D_DataBase alloc]init];
        [data openDB];
        D_MyMusic *myMusic = [[D_MyMusic alloc] init];
        myMusic.singer_name = [self.arr[num] objectForKey:@"singer_name"];
        myMusic.song_name = [self.arr[num] objectForKey:@"song_name"];
        myMusic.url = [[[self.arr[num]objectForKey:@"url_list"] firstObject] objectForKey:@"url"];
    myMusic.song_id = [self.arr[num] objectForKey:@"song_id"];
    myMusic.duration_time = [[[self.arr[num]objectForKey:@"url_list"] firstObject] objectForKey:@"duration"];
    myMusic.pic_url = [[[self.arr[num]objectForKey:@"mv_list"] firstObject] objectForKey:@"pic_url"];
    
        NSArray *tempArr = [NSArray array];
        tempArr = [data selectInfor];
        NSInteger tempNum = 0;
        for (NSInteger i = 0; i < tempArr.count; i++) {
            if ([[tempArr[i] song_name] isEqualToString:[self.arr[num] objectForKey:@"song_name"]]) {
                tempNum ++;
                [D_AlerterUIview showAlert:@"已经添加我喜欢!"];
            }
        }
        if (tempNum == 0) {
            [D_AlerterUIview showAlert:@"我喜欢!"];
            [data insertInforMyMusic:myMusic];
        }
        
 
}
#pragma mark - 收藏
- (void)collectAction:(UIButton *)button
{
//    [D_AlerterUIview showAlert:@"收藏成功!"];
    NSInteger num = button.tag;
    
    
    D_DataBase *data = [[D_DataBase alloc]init];
    [data openDB];
    D_MyMusic *myMusic = [[D_MyMusic alloc] init];
    myMusic.singer_name = [self.arr[num] objectForKey:@"singer_name"];
    myMusic.song_name = [self.arr[num] objectForKey:@"song_name"];
    myMusic.url = [[[self.arr[num]objectForKey:@"url_list"] firstObject] objectForKey:@"url"];
    myMusic.song_id = [self.arr[num] objectForKey:@"song_id"];
    myMusic.duration_time = [[[self.arr[num]objectForKey:@"url_list"] firstObject] objectForKey:@"duration"];
    myMusic.pic_url = [[[self.arr[num]objectForKey:@"mv_list"] firstObject] objectForKey:@"pic_url"];
    
    
        NSArray *tempArr = [NSArray array];
        tempArr = [data selectCollect];
        NSInteger tempNum = 0;
        for (NSInteger i = 0; i < tempArr.count; i++) {
            if ([[tempArr[i] song_name] isEqualToString:[self.arr[num] objectForKey:@"song_name"]]) {
                tempNum ++;
                [D_AlerterUIview showAlert:@"已经收藏!"];
            }
        }
        if (tempNum == 0) {
            [D_AlerterUIview showAlert:@"收藏成功!"];
            [data insertMyCollect:myMusic];
        }
        
        
 
    

    
    
}
#pragma mark - 删除
//- (void)deleteAction
//{
//    UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    [aler show];
//    [aler release];
//}

#pragma mark - collection协议方法
// section 个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.arr.count;
}
// item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}
// cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    D_MyMusicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor grayColor];
//    cell.alpha = 0.8;
    cell.backgroundColor = [UIColor clearColor];
    cell.alpha = 0.8;
    [cell.layer setBorderWidth:2];
    [cell.layer setBorderColor:[UIColor grayColor].CGColor];
    
    cell.singerLable.text = [self.arr[indexPath.section] objectForKey:@"singer_name"];
    cell.songLable.text = [self.arr[indexPath.section] objectForKey:@"song_name"];
    
    
    // 控制尾部buuton
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(280, 20, 20, 20);
    [button setBackgroundImage:[UIImage imageNamed:@"footerdown"] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    button.tag = indexPath.section;
 
    [button addTarget:self action:@selector(footerAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell addSubview:button];
    [cell.layer setCornerRadius:10];
    return  cell;
}

// item选择方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
 
    NSArray *str = [self.arr[indexPath.section] objectForKey:@"url_list"];
    NSString *playUrl = [str[0] objectForKey:@"url"];
        L_Singleton *play = [L_Singleton shareManager];
        [play playWithUrl:playUrl];
    
    NSLog(@"%@", [self.arr[indexPath.section] objectForKey:@"url_list"]);
 
    
}


- (void)getSongUrl
{
    
}


#pragma mark - 按钮显示footer
- (void)footerAction:(UIButton *)button
{
    
    if (button.tag == self.tagNum) {
        self.footerHight = 0;
        self.tagNum = 1111110;
    }else{
        self.footerHight = 80;
        self.tagNum = button.tag;
    }
    self.sectionNum = button.tag;
    [self.collection reloadData];
    
}

// 返回按钮
- (void)backAction
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
